package com.wangshuqi.boot.controller;

import com.alibaba.fastjson.JSON;
import com.wangshuqi.boot.entity.UserInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class SessionController {


    @RequestMapping("/set")
    public String setSessionAttribute(HttpSession session) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1);
        userInfo.setUsername("wangshuqi");
        userInfo.setPassword("123456");
        session.setAttribute("userInfo", JSON.toJSONString(userInfo));
        return "🔑 Session属性设置成功！";
    }

    @RequestMapping("/get")
    public String getSessionAttribute(HttpSession session, HttpServletRequest request) {
        // 方式一：
        Object value = session.getAttribute("userInfo");
        // 方式二：两种方式都可以取到redis中存入的session数据
        Object userInfo =  request.getSession().getAttribute("userInfo");
        // 打印至控制台查看数据
        System.out.println(userInfo != null ? userInfo.toString() : "null");
        System.out.println(JSON.toJSONString(userInfo));

        if (value != null) {
            return "📦 获取Session属性: " + JSON.toJSONString(value);
        } else {
            return "❗ Session属性不存在。";
        }
    }
}
